package com.dawn.module.cms.service.banner;

import com.dawn.framework.common.enums.CommonStatusEnum;
import com.dawn.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.dawn.module.cms.controller.admin.banner.vo.*;
import com.dawn.module.cms.dal.dataobject.banner.CmsBannerDO;
import com.dawn.framework.common.pojo.PageResult;
import com.dawn.framework.common.pojo.PageParam;
import com.dawn.framework.common.util.object.BeanUtils;

import com.dawn.module.cms.dal.mysql.banner.CmsBannerMapper;

import static com.dawn.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.dawn.module.cms.enums.ErrorCodeConstants.*;

/**
 * Banner 广告位 Service 实现类
 *
 * @author mamba 4 left
 */
@Service
@Validated
public class CmsBannerServiceImpl implements CmsBannerService {

    @Resource
    private CmsBannerMapper cmsBannerMapper;

    @Override
    public Long createBanner(CmsBannerSaveReqVO createReqVO) {
        // 插入
        CmsBannerDO banner = BeanUtils.toBean(createReqVO, CmsBannerDO.class);
        cmsBannerMapper.insert(banner);
        // 返回
        return banner.getId();
    }

    @Override
    public void updateBanner(CmsBannerSaveReqVO updateReqVO) {
        // 校验存在
        validateBannerExists(updateReqVO.getId());
        // 更新
        CmsBannerDO updateObj = BeanUtils.toBean(updateReqVO, CmsBannerDO.class);
        cmsBannerMapper.updateById(updateObj);
    }

    @Override
    public void deleteBanner(Long id) {
        // 校验存在
        validateBannerExists(id);
        // 删除
        cmsBannerMapper.deleteById(id);
    }

    private void validateBannerExists(Long id) {
        if (cmsBannerMapper.selectById(id) == null) {
            throw exception(BANNER_NOT_EXISTS);
        }
    }

    @Override
    public CmsBannerDO getBanner(Long id) {
        return cmsBannerMapper.selectById(id);
    }

    @Override
    public PageResult<CmsBannerDO> getBannerPage(CmsBannerPageReqVO pageReqVO) {
        return cmsBannerMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CmsBannerDO> getBannerListByPosition(Integer position) {
        return cmsBannerMapper.selectList(new LambdaQueryWrapperX<CmsBannerDO>()
                .eqIfPresent(CmsBannerDO::getPosition, position)
                .eq(CmsBannerDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .orderByDesc(CmsBannerDO::getSort));
    }

}